scala 数字阶乘 |
您所在的位置:网站首页 › 阶乘 代码 › scala 数字阶乘 |
scala 数字阶乘 Factorial of a number(n!) is the product of all positive numbers less than or equal to that number. 数字的阶乘(n!)是所有小于或等于该数字的正数的乘积。 The formula for factorial of a number is, 数字阶乘的公式是, n! = n * (n-1) * (n-2) * ... * 2 * 1 n! = 1 if n = 1 or 0Based on the above formula we can generate a recursive formula, 根据上述公式,我们可以生成一个递归公式, n! = n * (n-1)!Given a number, we have to find its factorial. 给定一个数字,我们必须找到它的阶乘。 Example: 例: Input: n = 6 Output: n! = 720 Explanation: 6! = 6*5*4*3*2*1 = 720The program will use this formula to find the factorial. As find factorial is a repetitive process. We have two methods to solve this problem, 程序将使用此公式查找阶乘。 发现阶乘是一个重复的过程。 我们有两种方法可以解决此问题, Using iteration 使用迭代 Using recursion 使用递归 1)递归方法查找数字的阶乘 (1) Recursive Approach to find factorial of a number)In recursion, we will call the same method multiple times until a condition is not satisfied. 在递归中,我们将多次调用同一方法,直到不满足条件为止。 Here, we will call the function factorial(n) in the following way: 在这里,我们将通过以下方式调用函数factorial(n) : Program: 程序: object myObject { def factorialRec(n: Int): Int ={ if(n def factorialIt(n: Int): Int ={ var factorial = 1 for(i |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |